<?php

/**
 * 景彤云链 SDK
 * @author chenyun
 */

namespace App\Service\VendorClient\Shopjtyl;
use App\Model\PssModel\ServiceConfig;
use App\Service\Code\Normal;
use App\Service\TaskServer\TaskWorker;
use Service\AppService\IdService;
use Hyperf\Utils\WaitGroup;
use App\Service\BaseService;

class ShopjtylApiClient extends BaseService
{
    private $account  = 'shopjtyl';
    protected $config;
    protected $RouteMap = [
        'createOrder'          => 'add_order_sync',
        'queryGoodsList'       => 'search_goods_detail',
    ];
    /**
     * 初始参数
     * @param obj $collection
     */
    public function __construct( $apiBody = [] ) 
    {
        $this->config = $apiBody;
    }
    
    /**
     * 创建订单
     */
    public function createOrder( $params = [] ) 
    {   
        ini_set('serialize_precision', 16);
        if( empty($params['supplierOrder']) || empty($params['orderGoods']) || empty($params['order']) || empty($params['binfo']) ) {
            return Normal::returnCode(Normal::FAIL,"except param supplierOrder or orderGoods or order or binfo");
        }
        //组装订单参数
        $orderInfo = $params['supplierOrder'];
        $order     = $params['order'];
        $binfo     = $params['binfo'];
        //运费
        $deliver_money  = $orderInfo['deliver_money'];
        //商品下单组
        $order_items = [];
        $productAmt = $TaxAmt = 0 ;
        foreach ($params['orderGoods'] as $key => $item )
        {
            //卖价
            $price              = $item['price'];
            //商品购买规格数量
            $spec_num           = $item['spec_num'];
            //商品购买数量(下单数量 X 起售数量)
            $quantity           = $item['quantity'];
            //实际购买数量
            $buyAcount          = $spec_num * $quantity;
            
            $singlePrice        = bcdiv($price, $spec_num,3);
            $singlePrice        = bcmul($singlePrice, 100,1);
            $singlePrice        = bcdiv(ceil($singlePrice), 100,2);
            $totalGoodsPrice    = bcmul($singlePrice, $buyAcount,2);    
            
            //商品组
            $order_items[] = [
                'goods_id'        => $item['supplier_store_id'],
                'goods_name'      => $item['goods_name'],
                'goods_sn'        => $item['supplier_skucode'],
                'goods_number'    => $buyAcount,
                'tax'             => 0,
            ];
            $productAmt = bcadd((string)$productAmt,(string)$totalGoodsPrice,2);
        }
        
        //实际下单金额
        $real_total_money   = $orderInfo['real_total_money'];        
        //订单总金额 = 含税商品总金额 + 运费 - 优惠金额
        $ActualPaidAmt      = bcadd((string)$productAmt,(string)$deliver_money,2);
        //优惠金额
        $discount_money     = bcsub((string)$ActualPaidAmt,$real_total_money,2);        
        //下单支付的时候支付信息
        $apply_extends      = @json_decode($orderInfo['apply_extends'],true);
        //支付时间
        $payTime            = empty($order['payTime']) ? $orderInfo['pay_time'] :$order['payTime'];
        //支付时间
        $pay_time           = $payTime ? $payTime : time();
        //支付流水号
        $pay_sn             = $order['paySerial']??$orderInfo['pay_sn'];
        
        //获取上游供应商支付方式路由
        $payCommanyCode = $apply_extends['payCommanyCode'] ?? ''; 
        $PayCompanyCode = $order['payCommanyCode'] ? $order['payCommanyCode'] : $payCommanyCode;
        $pay_value      = ServiceConfig::instance()->getConfigByEventsValue($this->account, ServiceConfig::TYPE_PAY, $PayCompanyCode);
        if (empty($pay_value)) {
            return Normal::returnCode(Normal::FAIL, "支付公司编码：【{$PayCompanyCode}】未映射，请联系管理员处理");
        } 
        //电商平台信息
        $enterpriseNum  = $apply_extends['enterpriseNum'] ?? '';
        $enterpriseName = $apply_extends['enterpriseName'] ?? '';
        $enterpriseNum  = $order['enterpriseNum'] ? $order['enterpriseNum'] : $enterpriseNum;
        $enterpriseName = $order['enterpriseName'] ? $order['enterpriseName'] : $enterpriseName;
        
        $province_name  = strpos($orderInfo['province'],"省") ? str_replace("省","",$orderInfo['province']) : $orderInfo['province'];
        $city_name      = strpos($orderInfo['city'],"市") ? str_replace("市","",$orderInfo['city']) : $orderInfo['city'];
        $district_name  = strpos($orderInfo['district'],"区") ? str_replace("区","",$orderInfo['district']) : $orderInfo['district'];
        
        //创建订单数据
        $data = [
            'act'                => $this->RouteMap["createOrder"],
            'api_version'        => $this->config["api_version"],
            'token'              => $this->config["token"],
            'user_id'            => $this->config["user_id"],
            'order_sn'           => $orderInfo['supplier_dsn'],
            'order_status'       => 1,
            'pay_status'         => 2,
            'order_time'         => $orderInfo['cd'],
            'pay_time'           => $pay_time,
            'consignee'          => $orderInfo['receive_name'],
            'country_name'       => "中国",
            'province_name'      => $province_name,
            'city_name'          => $city_name,
            'district_name'      => $district_name,
            'shipping_name'      => "快递",
            'detailed_addres'    => $orderInfo['receive_address'],
            'zipcode'            => "610000",
            'mobile'             => $orderInfo['recveive_phone'],
            'delivery_type'      => 5,
            'order_amount'       => (string)$real_total_money,
            'favourable'         => (string)$discount_money,
            'Is_allow_split'     => 0,
            'shipping_fee'       => (string)$deliver_money,
            'tax'                => (string)$TaxAmt,
            'pay_id'             => $pay_value,
            'pay_name'           => $orderInfo['buyer_realname'],
            'pay_no'             => $pay_sn,
            'full_name'          => $orderInfo['buyer_realname'],
            'card_num'           => $orderInfo['buyer_idcard'],
            'remark'             => $orderInfo['order_remark'],
            'order_items'        => json_encode($order_items)
        ];
        $requestParam = [
            'method'    => 'createOrder',
            'data'      => $data
        ];
        return $this->execute($requestParam);
    }
    
   
    /**
     * 查询商品信息
     */
    public function queryGoodsListBykeyNo( $params = [] )
    {
        $keyNos=$params["keyNos"];
        $newData=[];
        $count=count($keyNos);
        $wg = new WaitGroup();
        $wg->add($count);
         
        foreach ($keyNos as $key){
            co(function () use ($wg,$key,&$newData) {
               $data = [
                    'goods_id'     => $key,
                    'act'          => $this->RouteMap["queryGoodsList"],
                    'api_version'  => $this->config["api_version"],
                    'token'        => $this->config["token"],
                ];
                $requestParam = [
                    'method'    => 'queryGoodsList',
                    'data'      => $data,
                ];
                $response = $this->execute($requestParam);
                if ($response['code']==Normal::SUC && isset($response['data'])){
                    $newData[]=$response['data']["data_info"];
                }
                $wg->done();
            });
        }
        $wg->wait();
        
        $result = ['total' => count($newData),'data' => $newData];
        return Normal::returnCode(Normal::SUC, '获取成功', $result);
    
    }
  
    /**
     * CURL请求
     * @param $params
     * @return mixed
     */
    public function execute( $param = [] )  
    {
        if(empty($param['data']) ) {
            return Normal::returnCode(Normal::FAIL,"数据不能为空");
        }
        $method = $param['method'];
        $url = $this->config['baseurl'];
        $parameter = [
            [
                'tag'       => $this->account.'_'.$method,
                'uid'       => IdService::instance()->getOtherID(),
                'url'       => $url,
                'data'      => $param['data'],
                'method'    => 'post',
                'format'    => 'x-www-form-urlencoded',
                'header'    => [],
        
            ],
        ];
        if( in_array($method,['queryGoodsList']) ) {
            $resTask = TaskWorker::instance()->addTask($parameter,'handleDiableTask');
        } else {
            $resTask = TaskWorker::instance()->addTask($parameter);
        }
        $resTask = current($resTask);
        $res     = $resTask['response']['result']; 
     
        $xmlObj  = simplexml_load_string($res,"SimpleXMLElement", LIBXML_NOCDATA);
        $jsonStr = json_encode($xmlObj);
        $resHttp = json_decode($jsonStr, true);
        if( isset($resHttp['result']) && $resHttp['result']=="success" ) {
            return Normal::returnCode(Normal::SUC,"操作成功",$resHttp["info"]);
        }
        $message = isset($resHttp['info']) ? $resHttp['info'] : '请求失败';
        return Normal::returnCode(Normal::FAIL,$message);
    }
}